package com.peakmain.wanandroid.netmodule.net.http.params;

import android.support.annotation.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * author ：Peakmain
 * version : 1.0
 * createTime：2020/2/22
 * mail:2726449200@qq.com
 * describe：
 */
public class ProgressRequestBody extends RequestBody {

    protected RequestBody mRequestBody;
    protected UploadInterceptor mUploadInterceptor;

    protected CountingSink mCountingSink;

    public ProgressRequestBody(RequestBody requestBody, UploadInterceptor uploadInterceptor) {
        this.mRequestBody = requestBody;
        this.mUploadInterceptor = uploadInterceptor;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        try {
            return mRequestBody.contentLength();
        }catch (IOException e){
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        mCountingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(mCountingSink);
        mRequestBody.writeTo(bufferedSink);
        bufferedSink.flush();
    }



    protected final class CountingSink extends ForwardingSink {

        private long bytesWritten = 0;

        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            bytesWritten+=byteCount;
            if(mUploadInterceptor != null){
                mUploadInterceptor.onRequestProgress(bytesWritten,contentLength());
            }
        }
    }


    /**
     * 上传进度
     */
    public interface UploadInterceptor{

        void onRequestProgress(long bytesWritten, long contentLength);
    }
}
